<template>
  <div class="article bg-white">
    <!-- 用户信息 -->
    <van-cell-group :border="false" v-if="dynamic.user">
      <van-cell center class="tsline-bloger">
        <template slot="title">
          <span class="van-cell-text">{{dynamic.user.username}}</span>
          <div class="subtitle">
            <span>{{dynamic.publishTime}}</span>
            <span class="hsbar">·</span>
            <span>来自于 {{dynamic.device}}</span>
          </div>
        </template>
        <template slot="icon">
          <div class="user-avatar">
            <img :src="dynamic.user.portrait" />
            <i class="vip"></i>
          </div>
        </template>
        <template slot="right-icon">
          <van-button size="small" type="danger">关注</van-button>
        </template>
      </van-cell>
    </van-cell-group>
    <!-- 动态详情 -->
    <div
      class="rtf-html van-hairline--bottom"
      v-html="filter(dynamic.text)"
      v-on:click="handleTagClick($event)"
    ></div>
    <!-- 广告 -->
    <!-- 相关推荐 -->

    <!-- 转发、评论、点赞 -->
    <van-tabs
      v-model="activeIndex"
      sticky
      @click="onClick"
      class="dynamic-tabs"
      id="dynamic-tab-list"
    >
      <van-tab v-for="(tab, index) in tabs" :key="tab.id" :disabled="tab.disabled">
        <div slot="title">{{showTabName(tab, index)}}</div>
        <!-- 转发 -->
        <van-list
          v-model="tab.loading"
          :finished="tab.finished"
          @load="onLoadComments(index)"
          class="comment-list"
          v-if="tab.label=='retweet'"
        >
          <van-cell
            class="tsline-bloger comment-item"
            :clickable="actived"
            :border="false"
            v-for="item in tab.list"
            :key="item.id"
            @click="onView"
          >
            <template slot="title">
              <span class="van-cell-text">{{item.user.username}}</span>
              <div class="comment-content" v-on:click="handleTagClick($event)">{{filter(item.text)}}</div>
              <div class="subtitle">
                <span>{{item.time}}</span>
                <span class="hsbar">·</span>
                <span>转发 {{item.tools.retweets>0?item.tools.retweets:''}}</span>
              </div>
            </template>
            <template slot="icon">
              <div class="user-avatar">
                <img :src="item.user.avatar" />
                <i class="vip"></i>
              </div>
            </template>
          </van-cell>
        </van-list>
        <!-- 评论 -->
        <van-list
          v-model="tab.loading"
          :finished="tab.finished"
          @load="onLoadComments(index)"
          class="comment-list"
          v-else-if="tab.label=='comment'"
        >
          <van-cell
            class="tsline-bloger comment-item"
            :clickable="actived"
            :border="false"
            v-for="item in tab.list"
            :key="item.id"
            @click="onView"
          >
            <template slot="title">
              <span class="van-cell-text">{{item.user.username}}</span>
              <div class="subtitle">
                <span>{{item.time}}</span>
                <span class="hsbar">·</span>
                <span>{{item.device}}</span>
              </div>
              <div
                class="comment-content"
                v-html="filter(item.post)"
                @click.stop.prevent="handleTagClick($event)"
              ></div>
              <div class="comment-state">
                <span>{{item.time}}</span>
                <span class="hsbar">·</span>
                <span>{{item.reply_nums>0?item.reply_nums:''}}回复</span>
              </div>
            </template>
            <template slot="icon">
              <div class="user-avatar">
                <img :src="item.user.avatar" />
                <i class="vip"></i>
              </div>
            </template>
            <template slot="right-icon">
              <van-button size="small" @click.stop="onShow" class="btn-no-border">
                <van-icon name="like" />
                {{item.tools.likes}}
              </van-button>
            </template>
            <ul class="comment-inners" v-if="item.binmb.length>0">
              <li v-for="binmb in item.binmb" :key="binmb.id">
                <span>{{binmb.user.username}}</span>
                ：{{binmb.post}}
              </li>
              <li>
                <span>查看全部{{item.reply_nums}}条回复</span>
              </li>
            </ul>
          </van-cell>
        </van-list>
        <!-- 点赞 -->
        <van-list
          v-model="tab.loading"
          :finished="tab.finished"
          @load="onLoadComments(index)"
          class="comment-list"
          v-else-if="tab.label=='like'"
        >
          <van-cell
            class="tsline-bloger comment-item"
            :clickable="actived"
            :border="false"
            v-for="item in tab.list"
            :key="item.id"
            @click="onView"
          >
            <template slot="title">
              <span class="van-cell-text">{{item.user.username}}</span>
              <div class="subtitle">
                <span>{{item.time}}</span>
                <span class="hsbar">·</span>
                <span>{{item.device}}</span>
              </div>
            </template>
            <template slot="icon">
              <div class="user-avatar">
                <img :src="item.user.avatar" />
                <i class="vip"></i>
              </div>
            </template>
            <template slot="right-icon">
              <van-button size="small" @click.stop="onShow" class="btn-no-border">
                <van-icon name="color-like" />赞
              </van-button>
            </template>
          </van-cell>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>
<script>
import { Tag, Col, Icon, Cell, CellGroup, Tab, Tabs, Button, List } from 'vant'
import {
  refreshCommentList,
  setCommentCount,
  scrollToCommentList
} from '../../common/hybrid.js'
import { filterTags } from '../../common/helpers'
import { scroller } from 'vue-scrollto/src/scrollTo'

export default {
  components: {
    [Tag.name]: Tag,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Tab.name]: Tab,
    [Tabs.name]: Tabs,
    [Button.name]: Button,
    [List.name]: List,
    filterTags
  },
  data () {
    return {
      id: 0,
      activeIndex: 1,
      actived: true,
      time: 0,
      liked: true,
      cacheDuration: 30000,
      dynamic: {
        tools: {
          likes: 0,
          retweets: 0,
          comments: 0
        }
      },
      //
      tabs: [
        {
          id: 1,
          name: '转发',
          label: 'retweet',
          disabled: false,
          list: [],
          loading: false,
          finished: false,
          count: 0,
          isLoading: false,
          visible: false,
          meta: {
            totalCount: 0,
            pageCount: 0,
            currentPage: 0,
            perPage: 0
          }
        },
        {
          id: 2,
          name: '评论',
          label: 'comment',
          disabled: false,
          list: [],
          loading: false,
          finished: false,
          count: 0,
          isLoading: false,
          visible: false,
          meta: {
            totalCount: 0,
            pageCount: 0,
            currentPage: 0,
            perPage: 0
          }
        },
        {
          id: 3,
          name: '赞',
          label: 'like',
          disabled: false,
          list: [],
          loading: false,
          finished: false,
          count: 0,
          isLoading: false,
          visible: false,
          meta: {
            totalCount: 0,
            pageCount: 0,
            currentPage: 0,
            perPage: 0
          }
        }
      ],
      //
      list: [],
      loading: false,
      finished: false,
      count: 0,
      isLoading: false,
      show: false,
      visible: false,
      meta: {
        totalCount: 0,
        pageCount: 0,
        currentPage: 0,
        perPage: 0
      },
      formats: [
        'tsline-text',
        'tsline-thumb',
        'tsline-banner',
        'tsline-gralley'
      ]
    }
  },
  created: function () {
    console.log('-------created--------')
    refreshCommentList(() => {
      // 在此处刷新评论列表
    })
    // 设置评论数量
    setCommentCount(100)
    // 监听原生点击评论数量按钮的动作
    scrollToCommentList(() => {
      this.go2CommentList()
    })
  },
  mounted: function () {
    console.log('--------mounted-------')
  },
  activated: function () {
    this.id = this.$route.params.id
    let aid = this.$route.params.id
    let currentTime = new Date().getTime()

    if (
      this.$store.state.dynamicCurrentId !== aid ||
      currentTime - this.time > this.cacheDuration
    ) {
      console.log('--------onLoad-------')
      this.onLoad(aid, currentTime)
    }
  },
  methods: {
    filter (str) {
      return filterTags(str)
    },
    onLoad (id, currentTime) {
      let cacheArticle = this.$store.state.dynamicList.filter(function (
        item,
        index,
        self
      ) {
        if (item.id !== id) {
          return false
        }
        if (item.expired_at < currentTime) {
          self.splice(index, 1)
          return false
        }
        return true
      })

      if (cacheArticle[0]) {
        this.dynamic = cacheArticle[0]
      } else {
        this.axios
          .get('/dynamic/view', {
            params: { id: this.$route.params.id },
            headers: { FastMode: true }
          })
          .then(response => {
            this.dynamic = response.data
            this.time = currentTime
            this.dynamic.expired_at = currentTime + this.cacheDuration
            this.$store.state.dynamicList.push(this.dynamic)
          })
          .catch(function (error) {
            console.log(error)
          })
      }
    },
    onLoadComments (key) {
      console.log('key:' + key)
      console.log('key:' + this.activeIndex)

      let tab = this.tabs[key]
      let page = tab.meta.currentPage + 1

      this.axios
        .get('/dynamic/' + tab.label, {
          params: { id: this.id, pagepage: page },
          headers: { FastMode: true }
        })
        .then(response => {
          let data = response.data
          let itemCount = data.items.length
          if (itemCount > 0) {
            tab.list = tab.list.concat(data.items)
          }
          tab.meta = data.meta
          tab.loading = false
          if (tab.meta.pageCount <= tab.meta.currentPage || itemCount <= 0) {
            tab.finished = true
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    onClick (index) {
      console.log('index:' + index)
      this.activeIndex = index
    },
    onShow () {
      this.actived = false
      console.log('ONSHOW')
    },
    onView () {
      this.actived = true
      console.log('onView')
    },
    handleTagClick (event) {
      let clickevents = ['at', 'topic']
      if (
        event.target.nodeName !== 'SPAN' ||
        clickevents.indexOf(event.target.dataset.type) < 0
      ) {
        return
      }
      this.openNewWebview(event.target.dataset.type, {
        name: event.target.innerText
      })
    },
    openNewWebview (type, options) {
      console.log(type)
      console.log(options)
      this.$confirm(
        '即将打开新的WEBVIEW来显示当前匹配到的 ' +
          type +
          ' 内容，传递的参数为:' +
          options.name,
        {
          center: true,
          top: '50%',
          customClass: 'el-message-box-icon',
          dangerouslyUseHTMLString: true,
          showClose: false,
          closeOnClickModal: false,
          closeOnPressEscape: false
        }
      )
        .then(() => {
          // 查看详情
        })
        .catch(() => {
          // 分享一下
        })
    },
    arrayUnique (arr) {
      let result = []
      let hash = {}
      for (let i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem.id]) {
          result.push(elem)
          hash[elem.id] = true
        }
      }
      return result
    },
    showTabName (tab, index) {
      let nums = 0
      if (tab.label === 'retweet') {
        nums = this.dynamic.tools.retweets
      } else if (tab.label === 'comment') {
        nums = this.dynamic.tools.comments
      } else if (tab.label === 'like') {
        nums = this.dynamic.tools.likes
      }
      return tab.name + ' ' + nums
    },
    go2CommentList () {
      const scrollTo = scroller()
      scrollTo('#dynamic-tab-list')
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.comment-item {
  flex-wrap: wrap;
}
.comment-item /deep/ .van-cell__value {
  -webkit-box-flex: 0;
  -ms-flex: none;
  flex: none;
  order: 5;
  width: 100%;
  text-align: left;
  padding-left: 0.95rem;
}
.comment-state {
  font-size: 0.2rem;
  font-weight: 300;
  padding: 0.2rem 0;
}
.comment-inners {
  background: #f2f6f9;
  padding: 0.3rem;
}
.comment-inners li {
  font-size: 85%;
}
.comment-inners li span {
  color: #4b608f;
}
</style>
